package com.mes.web.controller.cb;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.mes.utils.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mes.entity.cb.Materiel;
import com.mes.entity.cb.PageBean;
import com.mes.service.cb.MaterieService;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;




/**
 * @ClassName: materieController 
 * @Description:物料基本信息
 * @Author cb
 * @Date 2017年12月22日 下午3:41:47 
 * @version 1.0
 */
@Controller
@RequestMapping("/materie")
public class MaterieController {
	
	@Resource
	private MaterieService materieService;
	
	/**
	 * 添加
	 * @param materiel  物料对象
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/materieAdd")
	public void materieAdd(Materiel materiel,HttpServletResponse response) throws Exception {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		
		//录入人和时间
		materiel.setRemark5("陈彬");
		materiel.setRemark6(formatter.format(new Date()));
		
		Integer affect=materieService.materieAdd(materiel);
		JSONObject jsonObject=new JSONObject();
		
		jsonObject.put("success", true);
		
		
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 分页
	 * @param response
	 * @param limit 页面
	 * @param offset 当前页
	 * @param name 物料名称
	 * @param materialmodel 物料型号
	 * @throws Exception
	 */
	@RequestMapping("/materieList")
	public void materieList(HttpServletResponse response,String limit,String offset,String name,String materialmodel) throws Exception {
		PageBean page = CustomUtils.paging(limit, offset);
		
		if (StringUtil.isNotEmpty(name)) {
			page.setName(name);
		}
		
		if (StringUtil.isNotEmpty(materialmodel)) {
			page.setMaterialmodel(materialmodel);
		}
		
		int total= materieService.getTotal(page);
		List<Materiel> list = materieService.planList(page);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 删除
	 * @param ids
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/materieDelete")
	public void materieDelete(String ids,HttpServletResponse response) throws Exception {

		int affect = materieService.materieDelete(ids);
		JSONObject jsonObject=new JSONObject();
		
		if (affect>0) {
			jsonObject.put("success", true);
		} else {
			jsonObject.put("success", false);
		}
		ResponseUtil.write(response, jsonObject);
	}

	@RequestMapping("/materie_selectById")
	public void materie_selectById(Long id,HttpServletResponse response) throws Exception {

		Materiel materiel =  materieService.materie_selectById(id);
		ResponseUtil.write(response,new Gson().toJson(materiel));
	}

	@RequestMapping("/Materie_Update")
	public void materie_Update(Materiel materiel,HttpServletResponse response) throws Exception {
		int affect = materieService.myModalUpdate(materiel);

		JSONObject jsonObject = new JSONObject();

		if (affect>0) {
			jsonObject.put("success", true);
		} else {
			jsonObject.put("success", false);
		}
		ResponseUtil.write(response,jsonObject);
	}

	/**
	 * 导出
	 * @param response
	 */
	@RequestMapping("/exportAll")
	public void exportAll(HttpServletResponse response) {

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟

		PageBean page = new PageBean();


		List<Materiel> list = materieService.planList(page);


		try {

			//创建HSSFWorkbook对象(excel的文档对象)
			HSSFWorkbook wb = new HSSFWorkbook();
			//建立新的sheet对象（excel的表单）
			HSSFSheet sheet=wb.createSheet("物料列表");

			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

			//在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
			HSSFRow row1=sheet.createRow(0);
			//创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
			HSSFCell cell=row1.createCell(0);
			//设置单元格内容
			cell.setCellValue("物料一览表");
			cell.setCellStyle(style);
			//合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
			sheet.addMergedRegion(new CellRangeAddress(0,0,0,11));
			//在sheet里创建第二行
			HSSFRow row2=sheet.createRow(1);
			//创建单元格并设置单元格内容
			row2.createCell(0).setCellValue("序号");
			row2.createCell(1).setCellValue("供应商");
			row2.createCell(2).setCellValue("车种");
			row2.createCell(3).setCellValue("物料名称");
			row2.createCell(4).setCellValue("物料型号");
			row2.createCell(5).setCellValue("颜色");
			row2.createCell(6).setCellValue("包装规格");
			row2.createCell(7).setCellValue("计量单位");
			row2.createCell(8).setCellValue("单价");
			row2.createCell(9).setCellValue("最低库存量");
			row2.createCell(10).setCellValue("最高库存量");
			//row2.createCell(11).setCellValue("安全库存量");


			for (int i = 0; i < list.size(); i++) {

				HSSFRow row3=sheet.createRow(i+2);
				row3.createCell(0).setCellValue(i+1);
				row3.createCell(1).setCellValue(list.get(i).getRemark15());
				row3.createCell(2).setCellValue(list.get(i).getRemark2());
				row3.createCell(3).setCellValue(list.get(i).getName());
				row3.createCell(4).setCellValue(list.get(i).getMaterialmodel());
				row3.createCell(5).setCellValue(list.get(i).getColor());
				row3.createCell(6).setCellValue(list.get(i).getRemark1());
				row3.createCell(7).setCellValue(list.get(i).getCompany());
				row3.createCell(8).setCellValue(list.get(i).getRemark3());
				row3.createCell(9).setCellValue(list.get(i).getRemark7());
				row3.createCell(10).setCellValue(list.get(i).getRemark8());
				//row3.createCell(11).setCellValue(list.get(i).getRemark4());

				//.....省略部分代码
			}


			//输出Excel文件
			OutputStream output=response.getOutputStream();
			response.reset();
			String ymdfomatTime = "物料表"+sdf.format(new Date());
			String fileName = new String(ymdfomatTime.getBytes("GBK"),"iso8859-1");
			response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
			response.setContentType("application/msexcel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			wb.write(output);
			output.close();


			} catch (Exception e) {
		}
	}

	@RequestMapping("/materie_import")
	public void materie_import(HttpServletRequest request , HttpServletResponse response , @RequestParam(value = "pic", required = false)MultipartFile[] file) throws Exception {
		//文件是否为空
		if (file == null) {
			return;
		}

		JSONObject jsonObject =new JSONObject();

		//文件路径
        String  savePath ;

		//文件名称
        String originalFilename ;

        InputStream is = null;



        for (MultipartFile mFile : file) {
			originalFilename =  mFile.getOriginalFilename();

            is = mFile.getInputStream();

            savePath = ((HttpSession) request).getServletContext().getRealPath("/WEB-INF/"+originalFilename);
            File newFile=new File(savePath);
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            mFile.transferTo(newFile);
		}

		List<Materiel> list = new ArrayList<>();

        Workbook workbook = null;
        // 创建一个表格
        try {
            workbook = new HSSFWorkbook(is);
            // 获得sheet1
        } catch (Exception e) {
            workbook = new XSSFWorkbook(is);
        }

        // 获得sheet1
        Sheet sheet = workbook.getSheetAt(0);
        // 读取每一行数据

        for (Row row : sheet) {

            int rowNum = row.getRowNum();
            /*if (rowNum == 0) {
                continue;
            }*/

            Cell cell = row.getCell(0);

            String supperName = null;
            if (cell != null) {
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                supperName = cell.getStringCellValue();
            }


            Cell cell1 = row.getCell(1);

            String remark2 =null;
            if (cell1 != null) {
                cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
                 remark2 = cell1.getStringCellValue();
            }


            Cell cell2 = row.getCell(2);

            String name =null;
            if (cell2 != null) {
                cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
                name = cell2.getStringCellValue();
            }


			//物料型号
            Cell cell3 = row.getCell(3);


            String materialModel =null;
            if (cell3 != null) {
                cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
                materialModel = cell3.getStringCellValue();
            }

            int count = materieService.materie_selectByMaterialmodel(materialModel);

            if (count > 0) {
				jsonObject.put("success", false);
				ResponseUtil.write(response,jsonObject);
            	return ;
			}


            Cell cell4 = row.getCell(4);

            String color =null;
            if (cell4 != null) {
                cell4.setCellType(HSSFCell.CELL_TYPE_STRING);
                color = cell4.getStringCellValue();
            }

            Cell cell5 = row.getCell(5);

            String remark1 =null;
            if (cell5 != null) {
                cell5.setCellType(HSSFCell.CELL_TYPE_STRING);
                remark1 = cell5.getStringCellValue();
            }

            Cell cell6 = row.getCell(6);

            String company =null;
            if (cell6 != null) {
                cell6.setCellType(HSSFCell.CELL_TYPE_STRING);
                company = cell6.getStringCellValue();
            }

            Cell cell7 = row.getCell(7);

            String remark3 =null;
            if (cell7 != null) {
                cell7.setCellType(HSSFCell.CELL_TYPE_STRING);
                remark3 = cell7.getStringCellValue();
            }

            Cell cell8 = row.getCell(8);

            String remark7 = null;
            if (cell8 != null) {
                cell8.setCellType(HSSFCell.CELL_TYPE_STRING);
                remark7 = cell8.getStringCellValue();
            }


            Cell cell9 = row.getCell(9);

            String remark8 = null;
            if (cell9 != null) {
                cell9.setCellType(HSSFCell.CELL_TYPE_STRING);
                remark8 = cell9.getStringCellValue();
            }



          /*  Cell cell10 = row.getCell(10);

            String remark4 = null;
            if (cell10 != null) {
                cell10.setCellType(HSSFCell.CELL_TYPE_STRING);
                remark4 = cell10.getStringCellValue();
            }*/


            Materiel materiel = new Materiel();

            Long supperId = materieService.materie_supper(supperName);

            materiel.setSupplierid(String.valueOf(supperId));


            materiel.setRemark2(remark2);
            materiel.setName(name);
            materiel.setMaterialmodel(materialModel);
            materiel.setColor(color);
            materiel.setRemark1(remark1);
            materiel.setCompany(company);
            materiel.setRemark3(remark3);
            materiel.setRemark7(remark7);
            materiel.setRemark8(remark8);
            //materiel.setRemark4(remark4);

            list.add(materiel);
            materiel = null;
        }

        if (list.size() > 0) {
            list.remove(0);
        }


        int toatl = materieService.materie_import(list);



		if (toatl>0) {
			jsonObject.put("success", true);
		} else {
			jsonObject.put("success", false);
		}
		ResponseUtil.write(response,jsonObject);

	}


    @RequestMapping("/downloadLocal")
    public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {

	    String data = "E:\\ide\\MES\\WebRoot\\datas\\Materiel.xls";

        try {
            // path是指欲下载的文件的路径。
            File file = new File(data);
            // 取得文件名。
            String filename = file.getName();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(data));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping("/materie_selectByMaterialmodel")
	public void materie_selectByMaterialmodel(String materialModel,HttpServletResponse response) throws Exception {
		int count = materieService.materie_selectByMaterialmodel(materialModel);
		JSONObject jsonObject =new JSONObject();
		if (count>0) {
			jsonObject.put("success", false);
		} else {
			jsonObject.put("success", true);
		}
		ResponseUtil.write(response,jsonObject);
	}




}
